var $;
layui.use(['jquery', 'element', 'table', 'form', 'layer'],function(){
    var element = layui.element;
    $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var createId = localStorage.getItem('createId');
    $('input[name=createId]').val(createId);
    $('input[name=updateId]').val(createId);
    //删除微圈
    removeMicroById = function removeMicroById(microcircleId){
        layer.confirm('是否确定删除此条数据', {
                icon: 3, title: '提示'
            },
            function (index) {
                //通过id删除表格数据
                $.ajax({
                    url: "/microcircle/deleteMicro",
                    type: "post",
                    dataType: "json",
                    data: {
                        "microcircleId": microcircleId,
                        "createId":createId
                    },
                    success: function (data) {
                        if(data.data){
                            layer.msg("删除成功");
                            location.reload();
                        }

                    },
                })
            }
        )

    }

    //查看微圈详情
    getMicroById = function getMicroById(microcircleId) {
        $.ajax({
            url: "/microcircle/getMicMsg",
            type: "post",
            dataType: "json",
            data: {
                "microcircleId": microcircleId,
                "createId":createId
            },
            success: function (data) {
                devicesMsg(data.data);
                localStorage.setItem("microcircleId",microcircleId);
            },
        })
    }

    function devicesMsg(data) {
        layer.open({
            type: 2,
            title: "查看微圈",
            area: ['1200px', '700px'],
            shade: 0,
            offset: 't',
            maxmin: true,
            content: "/MicroCircle/micro-circle-see.html",
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                obj.find('#artcleUrl').attr("src",data.artcleUrl);
                obj.find('#name').text(data.userName);
                obj.find('#createName').text(data.userName);
                obj.find('.artcleTitle').text(data.artcleTitle);
                obj.find('#artcleCategroyName').text(data.artcleCategroyName);
                obj.find('#createDate').text(data.createDate);
                obj.find('#createAccount').text(data.account);
                obj.find('#article').html(data.article);
                obj.find('#acticleHits').text(data.acticleHits);
                obj.find('#acticleLike').text(data.acticleLike);
                obj.find('#acticleShare').text(data.acticleShare);
                obj.find('#acticleCollection').text(data.acticleCollection);
                var trueName = localStorage.getItem("trueName");
                obj.find('input[name=trueName]').val(trueName);
                var account = localStorage.getItem("account");
                obj.find('input[name=account]').val(account);
            }
        });
    }

    var settingss = {
        view: {
            dblClickExpand: false,
            addDiyDom: addDiyDom//在view中增加这个方法-----这个解决方法
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "acticleCategroyId",   //节点数据中保存唯一标识的属性名称
                pIdKey: "artcleCatefroyParentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "artcleCategroyName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };
    //鼠标右键功能
    function onRightClick(event, treeId, treeNode) {
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }
    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            alert("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }
    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }
    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }
    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }
    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var artcleCatefroyParentId = nodes[0].acticleCategroyId;
        layer.open({
            type: 1,
            title: "添加节点",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: ['250px', '650px'],
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>添加分类：</label>"
                + "<input type='text' name='artcleCategroyName' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='文章分类'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var artcleCategroyName = $("#addNode").val();//节点名称
                var createId = $('input[name=createId]').val();//创建人id
                var jsProductCategroy = {
                    'artcleCatefroyParentId': artcleCatefroyParentId,
                    'artcleCategroyName': artcleCategroyName,
                    'createId': createId,
                }
                $.ajax({
                    url: '/micro/addActicleCategroy',
                    type:'post',
                    dataType: 'json',
                    data: jsProductCategroy,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }
    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var acticleCategroyId = nodes[0].acticleCategroyId;
        if (confirm("确认删除" + nodes[0].title + "商品类?")) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/micro/delActicleCategroy',
                data: {"acticleCategroyId": acticleCategroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        }
        return false;
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var acticleCategroyId = nodes[0].acticleCategroyId;
        layer.open({
            type: 1,
            title: '修改节点',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                "<label class='layui-input-label'>修改分类：</label>"
                +"<input type='text' name='artcleCategroyName' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='商品分类'>"
                +"</div></form>",
            btn : ['确定', '取消'],
            yes: function () {
                var artcleCategroyName = $("#updateNode").val();
                var updateId = $('input[name=updateId]').val();
                var jsProductCategroy = {
                    'acticleCategroyId': acticleCategroyId,
                    'artcleCategroyName': artcleCategroyName,
                    'updateId': updateId
                }
                if (artcleCategroyName.length != 0) {
                    $.ajax({
                        url: '/micro/updateActicleCategroy',
                        data: jsProductCategroy,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }
    //点击节点，展示对应类别下商品信息
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var acticleCategroyId = treeNode.acticleCategroyId;
        getTable(acticleCategroyId);
    }
    //限制节点字体显示超出6个字使用...代替
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 5;
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }
    var zTree, rMenu;
    $(document).ready(function(){
        $.ajax({
            type:"get",
            url:"/micro/getAllzTree",
            dataType:'json',
            success:function(res){
                zTree = $.fn.zTree.init($("#ztree"), settingss, res.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        });
        rMenu = $("#rMenu");
    });
    /* 表格开始 */
    var Microtable = table.render({
        elem: '#table',
        url: '/microcircle/getTable',
        toolbar: '#toptool',
        defaultToolbar: ['print', 'filter', 'exports'],
        page: true,
        limit: 15,
        limits: [10, 20, 30],
        cols: [[//定义列
            {type: 'checkbox', width: 80},//复选框靠左
            {
                type: 'orderId', title: '序号', align: 'center', width: 60, templet: function (data) {
                    return data.LAY_INDEX;
                }
            },
            {field: 'trueName', title: "用户名称", align: 'center'},
            {field: 'artcleTitle', title: "文章标题", align: 'center'},
            {field: 'createDate', title: "创建时间", align: 'center'},
            {field: 'account', title: "用户账号", align: 'center'},
            {field: 'acticleLike', title: "点赞数量", align: 'center'},
            {field: 'acticleCollection', title: "收藏数量", align: 'center'},
            {field: 'acticleReviews', title: "评论数量", align: 'center'},
            {field: 'acticleShare', title: "分享数量", align: 'center'},
            {
                title: '操作', align: 'center', templet: function (data) {
                    var tem = '<a  href="javascript:getMicroById(' + data.microcircleId + ');" style="color:rgb(13,171,158)">查看</a>' +
                        '<a  href="javascript:removeMicroById(' + data.microcircleId + ');" style="margin-left: 20px;color:rgb(13,171,158)">删除</a>';
                    return tem;
                }
            },
        ]],
    });
    function getTable(acticleCategroyId){
        var Microtable = table.render({
            elem: '#table',
            url: '/microcircle/getTable?acticleCategroyId='+acticleCategroyId,
            toolbar: '#toptool',
            defaultToolbar: ['print', 'filter', 'exports'],
            page: true,
            limit: 15,
            limits: [10, 20, 30],
            cols: [[//定义列
                {type: 'checkbox', width: 80},//复选框靠左
                {
                    type: 'orderId', title: '序号', align: 'center', width: 60, templet: function (data) {
                        return data.LAY_INDEX;
                    }
                },
                {field: 'trueName', title: "用户名称", align: 'center'},
                {field: 'artcleTitle', title: "文章标题", align: 'center'},
                {field: 'createDate', title: "创建时间", align: 'center'},
                {field: 'account', title: "用户账号", align: 'center'},
                {field: 'acticleLike', title: "点赞数量", align: 'center'},
                {field: 'acticleCollection', title: "收藏数量", align: 'center'},
                {field: 'acticleReviews', title: "评论数量", align: 'center'},
                {field: 'acticleShare', title: "分享数量", align: 'center'},
                {
                    title: '操作', align: 'center', templet: function (data) {
                        var tem = '<a  href="javascript:getMicroById(' + data.microcircleId + ');" style="color:rgb(13,171,158)">查看</a>' +
                            '<a  href="javascript:removeMicroById(' + data.microcircleId + ');" style="margin-left: 20px;color:rgb(13,171,158)">删除</a>';
                        return tem;
                    }
                },
            ]],
        });
    }
    /* 模糊查询 */
    form.on('submit(sub)',function (data) {
        console.log(data.field.trueName);
        Microtable.reload({
            url:'/microcircle/getTable?artcleTitle='+data.field.artcleTitle+'&trueName='+data.field.trueName+'&account='+data.field.account
        });
        return false;
    });
    /* 重置 */
    form.on('submit(subs)',function (data) {
        Microtable.reload({
            url:'/microcircle/getTable'
        });
    });
    /* 表格结束 */
    Refresh = function Refresh() {
        location.reload();
    }
    //返回
    goBack = function goBack() {
        parent.$('#beforeHref').val($('.layui-elem-quote').children('span').eq(0).text());
        parent.before();
        return false;
    }
});